#include "login.h"
#include "ui_login.h"
#include <QHostAddress>
#include<QMovie>

login::login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::login)
{
    ui->setupUi(this);
    this->s1 = new setip; //实例化setip
    this->client = new Form_client; //实例化form_client
    ui->lineEdit_ip->setText("127.0.0.1");
    ui->lineEdit_port->setText("8899");
    ui->mima->setEchoMode(QLineEdit::Password);
    ui->lineEdit_ip->hide();
    ui->lineEdit_port->hide();
    //创建套接字
    m_tcp = new QTcpSocket(this);
    //关联信号和槽函数
    connect(s1,SIGNAL(sendipData(QString)),this,SLOT(receiveripData(QString)));
    connect(s1,SIGNAL(sendportData(QString)),this,SLOT(receiverportData(QString)));
    connect(this,SIGNAL(sendmyid(QString)),this->client,SLOT(receiveridData(QString)));
    connect(this,SIGNAL(sendipData(QString)),this->client,SLOT(getipData(QString)));
    connect(this,SIGNAL(sendportData(QString)),this->client,SLOT(getportData(QString)));
    //给lab设置动画
    QMovie *movie = new QMovie(this);
    movie->setFileName(":/C:/denglu.gif");
    movie->start();
    ui->label->setMovie(movie);
    //接受验证消息
    connect(m_tcp,&QTcpSocket::readyRead,this,[=](){
        QByteArray returnmsg = m_tcp->readAll();
        if(returnmsg == "true")
        {
            //发送id信号
            QString idate = ui->zhanghao->text();
            emit sendmyid(idate);
            emit sendipData(ui->lineEdit_ip->text());
            emit sendportData(ui->lineEdit_port->text());
            this->hide();
            this->client->show();
        }
    });
}

login::~login()
{
    delete ui;
}

void login::receiveripData(QString data)
{
    ui->lineEdit_ip->setText(data);
}

void login::receiverportData(QString data)
{
    ui->lineEdit_port->setText(data);
}

void login::on_btnMin_clicked()
{
    this->showMinimized();
}

void login::on_btnClose_clicked()
{
    this->close();
}

void login::on_btnset_clicked()
{
    this->s1->show();
}

void login::on_btnlogin_clicked()
{
    QString ip = ui->lineEdit_ip->text();
    unsigned short port = ui->lineEdit_port->text().toUShort();
    m_tcp->connectToHost(QHostAddress(ip),port);
    QString username = ui->zhanghao->text();
    m_tcp->write(username.toUtf8());
    QString passward = ui->mima->text();
    m_tcp->write(passward.toUtf8());
}
